<template>
  <div>
    <t-form ref="form" colon reset-type="initial" :rules="FORM_RULES" :data="formData" @reset="onReset"
            @submit="onSubmit">
      <t-form-item :label="$t('dict.label.dictName')" name="dictName">
        <t-input-adornment :prepend="$t(formData.dictName)">
          <t-input v-model="formData.dictName" :placeholder="$t('dict.label.pl.dictName')"></t-input>
        </t-input-adornment>
      </t-form-item>
      <t-form-item :label="$t('dict.label.dictType')" name="dictType">
        <t-input v-model="formData.dictType" :placeholder="$t('dict.label.pl.dictType')"></t-input>
      </t-form-item>
      <t-form-item :label="$t('common.label.status')" name="status">
        <t-radio-group v-model="formData.status">
          <t-radio :value="0">{{ $t('common.label.status.0') }}</t-radio>
          <t-radio :value="1">{{ $t('common.label.status.1') }}</t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item :label="$t('common.attribute.describe')" name="remark">
        <t-textarea v-model="formData.remark" :placeholder="$t('common.attribute.pl.describe')"></t-textarea>
      </t-form-item>

      <t-space size="small">
        <t-checkbox @change="interShowChange" v-model="isInterShow">国际化</t-checkbox>
      </t-space>
      <div class="i18n-type-box" v-if="isInterShow">
        <t-form-item v-for="(item) in i18nResult.i18nInputs" :label="item.language" :name="item.language">
          <t-input v-model="item.i18nValue" :placeholder="$t('i18n.pl.trends', [item.language])"></t-input>
        </t-form-item>
      </div>
      <t-form-item>
        <t-space size="small">
          <t-button theme="primary" type="submit" :loading="loading">{{ $t('common.button.submit') }}</t-button>
          <t-button theme="default" variant="base" type="reset" :loading="loading">{{
              $t('common.button.reset1')
            }}
          </t-button>
        </t-space>
      </t-form-item>
    </t-form>
  </div>
</template>
<script setup lang="tsx">
import {onMounted, ref} from 'vue'
import {DictType} from '@/api/system/dict/types'
import {FormRules, MessagePlugin, SubmitContext} from 'tdesign-vue-next';
import {addDictType, editDictType, dictTypeInfo} from '@/api/system/dict';
import {ResultEnum} from '@/enums/httpEnum';
import i18n from '@/i18n';
import {useDictStore} from "@/store";
import {I18nInputs} from '@/api/system/i18n/types';
import {i18nInfo,updateI18n,saveI18n} from "@/api/system/i18n";

const emit = defineEmits(['submit-hook'])
const FORM_RULES = ref<FormRules>({
  dictName: [{required: true, message: i18n.global.t('dict.label.pl.dictName'), trigger: 'blur'}],
  dictType: [{required: true, message: i18n.global.t('dict.label.pl.dictType'), trigger: 'blur'}],
})
// 表单对象
const formData = ref<DictType>({
  id: '',
  dictName: '',
  dictType: '',
  status: 0,
});



const isInterShow = ref(false)

const dictStore = useDictStore()

const i18nResult = ref()  //用于查询i18n的结果回显

/**
 * 加载语言
 */
const loadI18n = async () => {
  const i18ns = await dictStore.i18nDictHook(initFromData);
  const i18nInputs: Array<I18nInputs> = [];
  i18ns.forEach(item => {
    i18nInputs.push({
      language: item.dictValue,
      i18nValue: undefined
    })
  })
  i18nResult.value.i18nInputs = i18nInputs
}

function interShowChange(e: boolean) {
  isInterShow.value = e
}


// 记录重置表单数据
const resetValue = ref({})
const dictTypeFromId = ref('');
const loading = ref(false);
/**
 * 重置表单
 */
const onReset = () => {
  loading.value = true
  if (dictTypeFromId.value) {
    initFromData(dictTypeFromId.value,null)
  }
  loading.value = false
};

/**
 * 初始化表单
 * @param dictTypeId 字典类型Id
 */
const initFromData = async (dictTypeId: string, i18nKey: string) => {
  isInterShow.value = false
  i18nResult.value = {}
  if (!dictTypeId) {
    formData.value = {
      id: '',
      dictName: '',
      dictType: '',
      status: 0,
      remark: ''
    }
    dictTypeFromId.value = undefined
    await loadI18n()
    return
  }
  dictTypeFromId.value = dictTypeId;
  const {code, result} = await dictTypeInfo(dictTypeId)
  if (ResultEnum.SUCCESS === code) {
    formData.value = result
    resetValue.value = result
  }

  //传入了i18n key 将语言查询回显
  if (i18nKey) {
    let res = await i18nInfo({i18nKey, i18nTag: 'common'})
    console.log(res, "语言内容回显")
    if(res.code == 200){
      i18nResult.value = res.result
      if(i18nResult.value.id){
        //如果有回显内容
        isInterShow.value = true
      }
    }else{
      loadI18n()
    }
  }
}

/**
 * 表单提交事件
 * @param param0 表单验证
 */
const onSubmit = async ({validateResult}: SubmitContext<DictType>) => {
  if (validateResult === true) {
    loading.value = true
    const api = formData.value.id ? editDictType : addDictType
    const res = await api(formData.value);


    if (res.code === ResultEnum.SUCCESS) {
      MessagePlugin.success(i18n.global.t('common.message.submitSuccess'));
      emit('submit-hook');
    } else {
      MessagePlugin.error(res.message);
    }



    //编辑或者添加字典国际化
    if(i18nResult.value.id){
      console.log(i18nResult.value)
      let res =  await updateI18n(i18nResult.value)
      if(res.code == 200){
        MessagePlugin.success(i18n.global.t('common.message.submitSuccess'));
      }
    }else{
      i18nResult.value.i18nTag = 'common'
      i18nResult.value.i18nKey = formData.value.dictName
      console.log(i18nResult.value)
      let res =  await saveI18n(i18nResult.value)
      if(res.code == 200){
        MessagePlugin.success(i18n.global.t('common.message.submitSuccess'));
      }
    }

    loading.value = false
  }
};

onMounted(async () => {

});

defineExpose({
  initFromData
})


</script>
<style lang="less">
.treeBox {
  border: 1px solid #ddd;
  overflow: auto;
  height: 300px;
  width: 100%;
}

.i18n-type-box {
  padding: 2vh 0;
  height: 35vh;
  overflow: auto;
}
</style>
